﻿namespace Leetcode.N0019;
public class Solution
{
    public ListNode RemoveNthFromEnd(ListNode head, int n)
    {
        int count = 0;
        var cur = head;
        ListNode preOfRemoveNode = null;

        while (cur != null)
        {
            count++;
            if (count == n + 1)
            {
                preOfRemoveNode = head;
            }
            else if (count > n + 1)
            {
                preOfRemoveNode = preOfRemoveNode.next;
            }

            cur = cur.next;
        }
        if (count == n)
        {
            var removeNode = head;
            head = head.next;
            removeNode.next = null;
        }
        else if (count > n)
        {
            var removeNode = preOfRemoveNode.next;
            preOfRemoveNode.next = removeNode.next;
            removeNode.next = null;
        }

        return head;
    }
}